package dao.impl;

import dao.BaseDao;
import dao.ComputerRoomDao;
import entity.ComputerRoom;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ComputerRoomDaoImpl extends BaseDao implements ComputerRoomDao {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    @Override
    public List<ComputerRoom> computerList() {
        conn = super.getConnection();
        List<ComputerRoom> list = new ArrayList<>();
        ComputerRoom computerRoom = null;
        try {
            String sql = "select * from computerroom order by computerNumber desc";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()){
                computerRoom = new ComputerRoom();
                computerRoom.setRoomId(rs.getInt("roomId"));
                computerRoom.setRoomName(rs.getString("roomName"));
                computerRoom.setComputerNumber(rs.getInt("computerNumber"));
                computerRoom.setManager(rs.getString("manager"));
                computerRoom.setLocation(rs.getString("location"));
                computerRoom.setState(rs.getInt("state"));
                list.add(computerRoom);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            super.getClose(conn,ps,rs);
        }
        return list;
    }

    @Override
    public int computerAdd(ComputerRoom computerRoom) {
        conn = super.getConnection();
        int count = 0;
        try {
            String sql = "insert into computerroom(roomName,computerNumber,manager,location,state)values(?,?,?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1,computerRoom.getRoomName());
            ps.setInt(2,computerRoom.getComputerNumber());
            ps.setString(3,computerRoom.getManager());
            ps.setString(4,computerRoom.getLocation());
            ps.setInt(5,computerRoom.getState());
            if(ps.executeUpdate()>0){
                count = 1;
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            super.getClose(conn,ps,rs);
        }
        return count;
    }

    @Override
    public int computerDelete(int id) {
        conn = super.getConnection();
        int count = 0;
        try {
            String sql = "delete from computerroom where roomId=?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1,id);
            if(ps.executeUpdate()>0){
                count = 1;
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            super.getClose(conn,ps,rs);
        }
        return count;
    }
}
